#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <signal.h>
#include <sys/epoll.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <string.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <stddef.h>
#include <linux/types.h>

#define EPRROM_ADDR 0x50

/**
 *  i2capp w "1234"
 *  i2capp r
*/
int main(int argc,char **argv)
{
    int fd = 0;
    int addr = 0x50;  // 设备地址
    char mem_reg = 0x0; // mem基地址
    int ret = 0;
    unsigned char i2c_read_buf[32];
    char *str = argv[2];
    unsigned char i2c_write_buf[2];

    fd = open("/dev/i2c-0", O_RDWR);
    if (fd < 0) {
        printf("open failed errno=%d\n", errno);
        printf("%s\n", strerror(errno)); 
        return -1;
    }

    // 设置非UU的i2c设备地址
    if (ioctl(fd, I2C_SLAVE, addr) < 0) {
        printf("I2C_SLAVE failed\n");
        exit(1);
    }
    // 设置UU的i2c设备地址
    //ioctl(fd, I2C_SLAVE_FORCE, addr);

    if (argv[1][0] == 'w') {
        while (*str) {    
            /* 从start到end */
            i2c_write_buf[0] = mem_reg;
            i2c_write_buf[1] = *str;

            /* 发送1个msg */
            ret = write(fd, i2c_write_buf, 2);
            if (ret < 0) {
                perror("Failed to I2C write");
                close(fd);
                return -1;
            }

            // 等待10ms
            usleep(20000);
            str++;
            mem_reg++;
        }
    } else if (argv[1][0] == 'r') {
        // 两个msgs, 一个w,一个r
        // i2c w
        /* 从start到end */
        i2c_write_buf[0] = 0x0; // 0x0地址

        /* 发送1个msg */
        ret = write(fd, i2c_write_buf, 1);
        if (ret < 0) {
            perror("Failed to I2C write");
            close(fd);
            return -1;
        }

        // i2c r
        ret = read(fd, i2c_read_buf, sizeof(i2c_read_buf));
        if (ret < 0) {
            perror("Failed to I2C write");
            close(fd);
            return -1;
        }
        
        printf("Get Data: %s\n", i2c_read_buf);
    }

    return 0;
}

